<?php

class YouNet_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	private $_app_unique_key;
	protected function _initYouNetPath()
	{
		defined('YOUNET_PATH')
			|| define('YOUNET_PATH', realpath(dirname(__FILE__)));
	}
	
	protected function _initBaseUrl() 
	{ 
        $this->bootstrap("frontController"); 
        $front = $this->getResource("frontController"); 
        $request = new Zend_Controller_Request_Http(); 
        $front->setRequest($request); 
		
		$base_url = Zend_Controller_Front::getInstance()->getBaseUrl();
		$this->_app_unique_key = 'ym_'.hash('MD5', $base_url);
	} 
	
	protected function _initDoctype()
    {
    	$this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
    }
    
    protected function _initSession()
    {		
    	Zend_Session::start();
    	$session = new Zend_Session_Namespace($this->_app_unique_key);
    	
    	Zend_Registry::getInstance()->set('session', $session);
    }
    
    protected function _initModules() 
    {
    	$front = $this->bootstrap("frontController")->frontController;
		$modules = $front->getControllerDirectory();
		$default = $front->getDefaultModule();
		
		set_include_path(get_include_path() . PATH_SEPARATOR . APPLICATION_PATH . '/modules/');
		            
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$controllers = array();
		foreach (array_keys($modules) as $module) {
			$directory = $front->getModuleDirectory($module);
			$controllers[strtolower($module)] = $directory . '/controllers';
						
//		    if ($module === $default) {
//		        continue;
//		    }	
		    
		    // init auto loader
		    $autoloader->pushAutoloader(new Zend_Application_Module_Autoloader(array(
                'namespace' => ucwords($module),
                'basePath' => $directory,
		    	'resourceTypes' => array(
			        'model' => array(
			            'path'      => 'models/',
			            'namespace' => 'Model',
			        )
            	)
            )));            
            
            // init auto loader namspace
            $autoloader->registerNamespace($module . '_');
        }
		
        $front->setControllerDirectory($controllers);
		$this->__initPaymentManager();
    }
    
    protected function _initAcl() 
    {    	
    	$acl = new Zend_Acl();
    	
    	$acl->addRole(new Zend_Acl_Role(Core_Role::ROLE_GUEST));
    	$acl->addRole(new Zend_Acl_Role(Core_Role::ROLE_USER), Core_Role::ROLE_GUEST);
    	
    	$acl->addResource('default:index');    	
    	$acl->allow(Core_Role::ROLE_GUEST, 'default:index', 'index');
    
		$registry = Zend_Registry::getInstance();
    	$registry->set('acl', $acl);
    }
    
    protected function _initYouNetApi()
    {
    	// init Social plugin
    	$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/social.ini', APPLICATION_ENV, array('allowModifications' => true));
    	YouNet_Api::getInstance()->initSocialPlugin($config->social);
    }
    
    protected function _initTranslator()
    {
		$language = 'en';
		Zend_Registry::set('language', 'en_US');
		
		$translate = new Zend_Translate(array(
			'adapter' => 'csv', 
    		'content' => APPLICATION_PATH.'/languages/'.$language.'/main.csv',
			'locale'  => $language,
			'delimiter' => ';'
		));
		
		// add translation source of all modules
		$front = Zend_Controller_Front::getInstance();
		$modules = $front->getControllerDirectory();
		foreach (array_keys($modules) as $module) {
			$file = APPLICATION_PATH.'/modules/'.ucwords($module).'/languages/'.$language.'/main.csv';
			if (file_exists($file))
			{
				$translate->addTranslation(
				    array(
				        'adapter' => 'csv', 
			    		'content' => $file,
						'locale'  => $language,
						'delimiter' => ';'
				    )
				);
			}
		}
		
		Zend_Registry::set('Zend_Translate', $translate);
		
		return $translate;
    }
    
    protected function _initModuleBootstrap()
    {
    	$front = Zend_Controller_Front::getInstance();
		$modules = $front->getControllerDirectory();

		foreach (array_keys($modules) as $module) {
    		$directory = $front->getModuleDirectory($module);			
            if (file_exists($directory . '/Bootstrap.php')) {
				$bootstrap_class = ucfirst($module) . '_Bootstrap';
				if (class_exists($bootstrap_class))
				{
					$bootstrap = new $bootstrap_class($this->getApplication());
					$bootstrap->bootstrap();
				}
            }
		}
    }
    
    protected function _initTimezone()
    {
    	date_default_timezone_set('GMT');
    }
    
    protected function _initP3P()
    {
    	header('P3P: CP="NON DSP COR CURa ADMa DEVa CUSa TAIa OUR SAMa IND"');
    }

	protected function _initCache()
	{
		$options		= $this->getOptions();		
		$backendOptions	= array();
		if( isset($options['cache']) && isset($options['cache']['backend']) ){
			$backendOptions = $options['cache']['backend'];
		}		
		$cacheManager	= new YouNet_Cache_Manager($this->_app_unique_key, $backendOptions);
		Zend_Registry::set('cache_manager', $cacheManager);
		
		$this->__initDbCache();
	}
	
	public function __initDbCache()
	{
		Zend_Db_Table_Abstract::setDefaultMetadataCache(YouNet_Util::getObjectFileCache());
	}
	
	public function _initStorage()
	{
		$options = $this->getOptions();

		if (isset($options['storage'])) 
		{
			$classname = 'YouNet_Storage_' . $options['storage']['adapter'];
			$storage = new $classname($options['storage']['params']);			
		}
		else
		{
			$storage = new YouNet_Storage_File();
		}
		
		$base_url = Zend_Controller_Front::getInstance()->getBaseUrl();		
		if ($storage instanceof YouNet_Storage_S3)
		{
			define('STATIC_PATH', $base_url);
			
    		$static_url = $options['storage']['params']['staticUrl'];			
			//if HTTPS and staticHttpsUrl is available: use staticHttpsUrl instead
			if (!empty($_SERVER['HTTPS']) && !empty($options['storage']['params']['staticHttpsUrl']))
			{
				$static_url = $options['storage']['params']['staticHttpsUrl'];
			}
			
    		define('STATIC_URL', $static_url . $base_url);                        
		}
		else
		{
			define('STATIC_PATH', INDEX_PATH);
    		define('STATIC_URL', '//' . $_SERVER['SERVER_NAME'] . $base_url);    			
		}
		$this->__initRepositoryUrl();
		$this->__initPath();
		Zend_Registry::set('storage', $storage);
	}
	
	public function __initPath()
	{
		// to be defined by each application	
	}
	
	private function __initRepositoryUrl()
	{
		if( $this->getOption('repositoryUrl') )
		{
			define('REPOSITORY_URL',$this->getOption('repositoryUrl'));
		}
		else
		{
			define('REPOSITORY_URL',STATIC_URL);
		}
	}
	
	public function __initPaymentManager()
	{
		// to be defined by each application
	}
	
	public function _initGoogleAnalytics()
	{
		$options = $this->getOptions();
		if (isset($options['googleAnalytics']))
		{
			define('GOOGLE_ANALYTICS_ID', $options['googleAnalytics']['id']);
		}
		else
		{
			define('GOOGLE_ANALYTICS_ID', '');
		}
	}
	
	protected function _initRouter()
	{
		$front		= Zend_Controller_Front::getInstance();
		$route		= new YouNet_Controller_Router_Route(
			':module/:id_page/:controller/:action/*',
			array(
				'module'		=> 'tab',
				'controller'	=> 'index',
				'action'		=> 'index'
			),
			array(
				'id_page'		=> '\d+',
				'module'		=> '^(tab|page)$'
			)
		);
		$front->getRouter()->addRoute('tab', $route);
	}
}
